package 多线程.力扣1114_按序打印;

public class OrderedExecution3 {

    // 状态变量，1=T1执行, 2=T2执行, 3=T3执行
    private volatile int turn = 1;

    public void printOne() {
        System.out.println(Thread.currentThread().getName() + ": one");
        // 更新状态，轮到下一个线程
        turn = 2;
    }

    public void printTwo() {
        while (turn != 2);
        System.out.println(Thread.currentThread().getName() + ": two");
        turn = 3;
    }

    public void printThree() {
        while (turn != 3);
        System.out.println(Thread.currentThread().getName() + ": three");
    }

    public static void main(String[] args) {
        OrderedExecution3 orderedExecution = new OrderedExecution3();

        Thread t1 = new Thread(orderedExecution::printOne, "T1");
        Thread t2 = new Thread(orderedExecution::printTwo, "T2");
        Thread t3 = new Thread(orderedExecution::printThree, "T3");
        
        // 启动顺序不重要，同步机制会保证执行顺序
        t2.start();
        t3.start();
        t1.start();


    }
}